<script setup lang="ts" name="AddVaccineLibrary">
import dDialog from '@/components/dDialog/dDialog.vue'
import dFrom from '@/components/dFrom/dFrom.vue'
import {FromItem} from '@/components/dFrom/dFrom'
import {PropType, reactive, ref, watch} from 'vue'
import {ElMessage, FormRules} from 'element-plus'
import {Letter, NoChinese, NotLeadingAndTrailingSpaces} from '@/util/common'
import {saveVaccineStore, VaccineStoreList} from '@/api/medicalExaminerDesk/beginPhysicalExamination/vaccinationHistory'
import {getUpperCase} from '@/api/medicalExaminerDesk/beginPhysicalExamination/mainMedication'
const props = defineProps({
  //显示
  showDialog: {
    type: Boolean,
    required: true
  },
  dialogType: {
    type: String,
    required: true
  },
  vaccineData: {
    type: Object as PropType<VaccineStoreList>,
    required: true
  }
})

const emits = defineEmits(['close'])

//表单清除控制
const resetFieldsFlag = ref(false)
const validateFlag = ref(false)

// 保存加载
const showSaveLoading = ref<boolean>(false)

// 是否转换拼音码
const convertPinyin = ref<boolean>(!props.vaccineData?.pinyinCode)

// 空数据
const emptyData: VaccineStoreList = {}

// 是否保存并且继续
const continueFlag = ref(false)

// 新增疫苗
const fromData = reactive<VaccineStoreList>({...props.vaccineData})

//表单项
const fromItems = ref<Array<FromItem>>([
  {
    label: '疫苗代码',
    prop: 'inocCode',
    placeholder: '请输入疫苗代码',
    type: 'input'
  },
  {
    label: '疫苗名称',
    prop: 'inocName',
    type: 'slot',
    slotName: 'inocName'
  },
  {
    label: '拼音码',
    prop: 'pinyinCode',
    placeholder: '请输入拼音码',
    type: 'input'
  },
  {
    label: '接种机构',
    prop: 'unitsName',
    placeholder: '请输入接种机构',
    type: 'input'
  }
])

const rules = reactive<FormRules>({
  inocCode: [
    {required: true, message: '请输入疫苗代码', trigger: ['change', 'blur']},
    {
      message: '最多50位字母、数字、字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母、数字、字符',
      pattern: NoChinese,
      trigger: ['change', 'blur']
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  inocName: [
    {
      required: true,
      message: '请输入疫苗名称',
      trigger: ['change', 'blur']
    },
    {
      message: '最多100个字符',
      trigger: ['change', 'blur'],
      max: 100
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ],
  pinyinCode: [
    {
      message: '最多50个字符',
      trigger: ['change', 'blur'],
      max: 50
    },
    {
      message: '请输入字母',
      pattern: Letter,
      trigger: ['change', 'blur']
    }
  ],
  unitsName: [
    {
      message: '最多100个字符',
      trigger: ['change', 'blur'],
      max: 100
    },
    {
      message: '首尾不能为空格',
      pattern: NotLeadingAndTrailingSpaces,
      trigger: ['change', 'blur']
    }
  ]
})

/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onCancel = () => {
  emits('close')
}
/**
 * @description: 关闭弹窗
 * @return {*}
 */
const onClose = () => {
  emits('close')
}

/**
 * @description: 保存
 * @return {*}
 */
const onConfirm = () => {
  validateFlag.value = !validateFlag.value
  continueFlag.value = false // 保存不继续
}

/**
 * @description: 保存并继续
 * @return {*}
 */
const onContinueConfirm = () => {
  validateFlag.value = !validateFlag.value
  continueFlag.value = true // 保存并且继续
}

/**
 * @description: 根据中文获取拼音首字母大写
 * @return {*}
 */
const onUpperCaseChange = (e) => {
  // 没有拼音码才触发自动转换
  if (convertPinyin.value) {
    const chinese = e.replace(/[^\u4e00-\u9fa5]/gi, '')
    e &&
      getUpperCase({drugName: chinese}).then((res) => {
        fromData.pinyinCode = res.data?.data || ''
      })
  }
}

watch(
  () => fromData.pinyinCode,
  () => {
    // 清空拼音码要继续触发转换
    !fromData.pinyinCode && (convertPinyin.value = true)
  }
)

//表单验证通过事件
const onSubmit = () => {
  showSaveLoading.value = true
  const params = {
    id: fromData.id,
    inocCode: fromData.inocCode, // 疫苗代码
    inocName: fromData.inocName, // 疫苗名称
    pinyinCode: fromData.pinyinCode || null, // 拼音码
    unitsName: fromData.unitsName || null // 接种机构
  }
  saveVaccineStore(params)
    .then(() => {
      ElMessage.success('保存成功！')
      resetFieldsFlag.value = !resetFieldsFlag.value
      continueFlag.value ? Object.assign(fromData, emptyData) : emits('close')
    })
    .finally(() => {
      showSaveLoading.value = false
    })
}
</script>
<template>
  <d-dialog
    :title="dialogType === 'edit' ? '编辑疫苗' : '新增疫苗'"
    :show-dialog="showDialog"
    :width="868"
    :show-save-loading="showSaveLoading"
    @cancel="onCancel"
    @close="onClose"
    @confirm="onConfirm"
  >
    <d-from
      label-position="right"
      :label-width="100"
      :reset-fields-flag="resetFieldsFlag"
      :validate-flag="validateFlag"
      :form-data="fromData"
      :rules="rules"
      :form-items="fromItems"
      :form-line-num="1"
      @submit="onSubmit"
    >
      <template #inocName>
        <el-input v-model="fromData.inocName" placeholder="请输入疫苗名称" clearable @blur="onUpperCaseChange(fromData.inocName)" />
      </template>
    </d-from>
    <template v-if="dialogType === 'add'" #append>
      <el-button type="primary" :loading="showSaveLoading" @click="onContinueConfirm">
        保存并继续
      </el-button>
    </template>
  </d-dialog>
</template>
<style scoped lang="less"></style>
